<?php

App::uses('AppController', 'Controller');

class MembersController extends AppController {

    public $uses = array('Member', 'MemberImage', 'OrganisationMember', 'MemberAccount', 'OrganisationAccount');
    public $components = array('AccountEmail');
    public $layout = "app";

    public function beforeFilter() {
        parent::beforeFilter();

        $this->autoRender = false;
    }

    /**
     * Returns a list of members or a single member from the database. 
     * 
     * params - multiple members
     *  - organisation_id
     *  - limit
     *  - offset
     * 
     * params - single member
     *  - organisation_id
     *  - member_id
     */
    public function index() {

        $data = $this->request->data;
        
        $organisation_id = isset($data['organisation_id']) ? $data['organisation_id'] : null;
        $offset = isset($data['offset']) ? $data['offset'] : 0;
        $limit = isset($data['limit']) ? $data['limit'] : 40;
        $member_id = isset($data['member_id']) ? $data['member_id'] : null;
        $sort_order = isset($data['sort_order']) ? $data['sort_order'] : 'recent';
        $status = isset($data['status']) ? $data['status'] : 'member';

        if ($member_id != null) {
            $member = $this->Member->find('first', array(
                'contain' => array(
                    'MemberImage', 'MemberSpouse'
                ),
                'conditions' => array(
                    'Member.id' => $member_id
                )
            ));

            return $this->_response($member);
        } 
        
        else if ($organisation_id != null) {
            $members = $this->OrganisationMember->getMembersForList($organisation_id, $offset, $limit, $sort_order, $status);

            return $this->_response($members);
        } 
        
        else {
            return $this->_response(array('status' => 'error', 'message' => 'Invalid Parameters Passed'));
        }
    }

    public function create() {

        $data = $this->request->data;

        if (isset($data['Member'])) {
            $this->autoRender = false;

            $result = $this->Member->saveAll($data);

            if ($result) {

                $this->OrganisationMember->save(array(
                    'id' => isset($data['OrganisationMember']) ? $data['OrganisationMember']['id'] : null,
                    'organisation_id' => $data['Member']['organisation_id'],
                    'organisation_no' => $data['Member']['organisation_no'],
                    'approved' => 0,
                    'member_id' => $this->Member->id
                ));

                if (isset($data['MemberImage']['id']) && $data['MemberImage']['id'] != '') {
                    $this->MemberImage->assign($data['MemberImage']['id'], $this->Member->id);
                }
            }

            return $this->_response(array(
                        'status' => $result ? 'success' : 'failed',
                        'message' => $result ? 'Profile Updated Successfully' : 'Profile Update Failed'
            ));
        }
    }

    /**
     * action to flag a member as deleted
     */
    public function delete() {
        $this->autoRender = false;

        if (isset($_POST['member_id']) && $_POST['organisation_id']) {
            $this->Member->deleteMember($_POST['organisation_id'], $_POST['member_id']);

            return $this->_response(array('status' => 'success'));
        } else {
            return $this->_response(array('status' => 'error', 'message' => 'invalid parameters passed'));
        }
    }

    public function login() {

        $rules = array(
            'required' => 'username, password'
        );

        $data = $this->request->data;

        $validated = $this->_validateParams($rules, $data);

        if ($validated != "NO_ERROR") {
            return $validated;
        }

        extract($data);

        $login = $this->MemberAccount->attempt_login($username, $password, isset($remember_me) ? $remember_me : false);

        if ($login) {
            return $this->_response(array('status' => 'success', 'account' => $login['account'], 'session' => $login['session']));
        } else {
            return $this->_response(array('status' => 'failed', 'message' => 'Invalid Information Provided'));
        }
    }

    public function clef_login() {

        $rules = array(
            'required' => 'username'
        );

        $data = $this->request->data;

        $validated = $this->_validateParams($rules, $data);

        if ($validated != "NO_ERROR") {
            return $validated;
        }

        extract($data);

        $login = $this->MemberAccount->clef_login($username);

        if ($login) {
            return $this->_response(array('status' => 'success', 'account' => $login['account'], 'session' => $login['session']));
        } else {
            return $this->_response(array('status' => 'failed', 'message' => 'Invalid Information Provided'));
        }
    }
    
    public function logout() {
        
        $rules = array(
            'required' => 'member_account_id, session_id'
        );

        $data = $this->request->data;

        $validated = $this->_validateParams($rules, $data);

        if ($validated != "NO_ERROR") {
            return $validated;
        }

        extract($data);
        
        $response = $this->MemberAccount->MemberAccountSession->end($member_account_id, $session_id);
        
        return $this->_response($response);
    }
    
    public function validate_login() {
        $rules = array(
            'required' => 'username, password'
        );

        $data = $this->request->data;

        $validated = $this->_validateParams($rules, $data);

        if ($validated != "NO_ERROR") {
            return $validated;
        }

        extract($data);
        
        $login = $this->MemberAccount->attempt_login($username, $password, false);

        if ($login) {
            return $this->_response(array('status' => 'success', 'valid' => true));
        } else {
            return $this->_response(array('status' => 'failed', 'valid' => false));
        }
    }

    public function removeChild() {
        $this->autoRender = false;

        $rules = array(
            'required' => 'member_id, child_id'
        );

        $data = $this->request->data;

        $validated = $this->_validateParams($rules, $data);

        if ($validated != "NO_ERROR") {
            return $validated;
        }

        extract($data);

        $result = $this->Member->removeChild($member_id, $child_id);

        return $this->_response(array(
                    'status' => $result ? 'success' : 'failed',
                    'message' => $result ? 'Removed Successfully' : 'Removal Failed'
        ));
    }

    public function account($action = 'fetch') {
        $this->autoRender = false;

        $data = $this->request->data;

        $response = array();

        switch ($action) {
            case 'fetch': 
                $rules = array(
                    'required' => 'username'
                );

                $validated = $this->_validateParams($rules, $data);

                if ($validated != "NO_ERROR") {
                    return $validated;
                }
                
                $account = $this->MemberAccount->getMemberAccount($data['username']);
                
                if( $account ) {
                    $response = array('status' => 'success', 'data' => $account);
                }
                else {
                    $response = array('status' => 'failed', 'message' => 'Member account not found');
                }
                
                break;
            
            case 'create':
                $rules = array(
                    'required' => 'first_name, last_name, dob, gender, username, password'
                );

                $validated = $this->_validateParams($rules, $data);

                if ($validated != "NO_ERROR") {
                    return $validated;
                }

                $response = $this->MemberAccount->createAccount($data);

                // account created, send activation email
                if ($response['status'] == 'success') {
                    $email_response = $this->AccountEmail->emailMemberAccountActivation($response['account']['MemberAccount']['id'], 'website');

                    $response['message'] = array($response['message'], $email_response['message']);
                }

                break;

            case 'activate':
                $rules = array(
                    'required' => 'username, auth_hash'
                );

                $validated = $this->_validateParams($rules, $data);

                if ($validated != "NO_ERROR") {
                    return $validated;
                }

                extract($data);

                $response = $this->MemberAccount->activate($username, $auth_hash);
                break;
                
            case "change_password":
                $response = $this->MemberAccount->changePassword($data['account_id'], $data['new_password']);

                if( $response['status'] == 'success' ) {
                    $this->AccountEmail->emailPasswordChangeNotification($data['account_id']);
                }
                
                break;
                
            case "reset_password":
                $rules = array(
                    'required' => 'username'
                );

                $validated = $this->_validateParams($rules, $data);

                if ($validated != "NO_ERROR") {
                    return $validated;
                }
                
                $account = $this->MemberAccount->getMemberAccount($data['username']);
                
                if( !$account ) {
                    $response = array('status' => 'failed', 'message' => 'No account for supplied username');
                } else {
                    $response = $this->AccountEmail->emailPasswordReset($data['username']);
                }
                
                break;
        }

        return $this->_response($response);
    }

    public function validate_session() {

        $data = $this->request->data;

        $rules = array(
            'required' => 'member_account_id, session_device_id'
        );

        $validated = $this->_validateParams($rules, $data);

        if ($validated != "NO_ERROR") {
            return $validated;
        }

        extract($data);
        
        $validation = $this->MemberAccount->MemberAccountSession->validate($member_account_id, $session_device_id);
        
        return $this->_response($validation);
    }

    public function remove_phone_number() {
        
        $data = $this->request->data;

        $rules = array(
            'required' => 'member_id, member_phone_number_id'
        );

        $validated = $this->_validateParams($rules, $data);

        if ($validated != "NO_ERROR") {
            return $validated;
        }

        extract($data);
        
        $updated = $this->Member->MemberPhoneNumber->updateAll(array(
            'MemberPhoneNumber.active' => 0
        ), array(
            'MemberPhoneNumber.member_id' => $member_id,
            'MemberPhoneNumber.id' => $member_phone_number_id
        ));
        
        return $this->_response(array('status' => 'success', 'message' => 'Delete operation completed'));
    }
    
    public function remove_email() {
        
        $data = $this->request->data;

        $rules = array(
            'required' => 'member_id, member_email_id'
        );

        $validated = $this->_validateParams($rules, $data);

        if ($validated != "NO_ERROR") {
            return $validated;
        }

        extract($data);
        
        $updated = $this->Member->MemberEmail->updateAll(array(
            'MemberEmail.active' => 0
        ), array(
            'MemberEmail.member_id' => $member_id,
            'MemberEmail.id' => $member_email_id
        ));
        
        return $this->_response(array('status' => 'success', 'message' => 'Delete operation completed'));
    }
    
    public function organisations() {
        $data = $this->request->data;

        $rules = array(
            'required' => 'member_id'
        );

        $validated = $this->_validateParams($rules, $data);

        if ($validated != "NO_ERROR") {
            return $validated;
        }

        extract($data);
        
        $member_account = $this->MemberAccount->find('first', array(
            'conditions' => array(
                'MemberAccount.member_id' => $member_id,
                'MemberAccount.active' =>1
            ),
            'recursive' => -1
        ));
        
        $m_org_ids = $this->OrganisationMember->find('list', array(
            'fields' => array('organisation_id'),
            'conditions' => array(
                'OrganisationMember.member_id' => $member_id
            )
        ));
        
        $a_org_ids = $this->OrganisationAccount->find('list', array(
            'fields' => array('organisation_id'),
            'conditions' => array(
                'OrganisationAccount.member_account_id' => $member_account['MemberAccount']['id']
            )
        ));
        
        $org_ids = array_unique( array_values(array_merge($m_org_ids, $a_org_ids)) );
        
        $organisations = $this->Organisation->find('all', array(
            'contain' => array(
                'OrganisationMember' => array(
                    'conditions' => array(
                        'OrganisationMember.member_id' => $member_account['MemberAccount']['member_id'],
                        'OrganisationMember.active' => 1
                    )
                ),
                'OrganisationAccount' => array(
                    'OrganisationRole',
                    'conditions' => array(
                        'OrganisationAccount.member_account_id' => $member_account['MemberAccount']['id'],
                        'OrganisationAccount.active' => 1
                    )
                )
            ),
            'conditions' => array(
                'Organisation.id' => $org_ids,
                'Organisation.active' => 1
            )
        ));
        
        foreach($organisations as &$org) {
            $members = $this->OrganisationMember->getTotalMembers($org['Organisation']['id']);
            
            $org['Organisation']['members'] = $members;
        }
        
        return $this->_response(array('org_ids' => $org_ids, 'organisations' => $organisations));
    }
}
